package com.coffee.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.coffee.framework.common.exception.CustomException;
import com.coffee.framework.common.result.R;
import com.coffee.framework.common.result.ResultCode;
import com.coffee.framework.storage.strategy.FileStorageStrategy;
import com.coffee.framework.storage.strategy.context.FileStorageContext;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


/**
 * <p>
 * 通用common 前端控制器
 * </p>
 *
 * @author Kevin
 */
@RestController
@RequestMapping("/common")
@Slf4j
@AllArgsConstructor
public class CommonController {

    private FileStorageContext fileStorageContext;

    @PostMapping("/upload")
    @SneakyThrows
    public R upload(MultipartFile file, HttpServletRequest request) {
        String bizPath = request.getParameter("bizPath");
        if (StrUtil.isBlank(bizPath)) {
            throw new CustomException(ResultCode.PARAM_MISS.getMessage());
        }
        if (Objects.isNull(file)) {
            throw new CustomException(ResultCode.PARAM_MISS.getMessage());
        }
        FileStorageStrategy fileStorageStrategy = fileStorageContext.getContext();
        String url = fileStorageStrategy.upload(file, bizPath);
        return R.success(url);
    }

}
